/**
 * 
 */
package com.fox.webapp.persistent.impl;

import static org.springframework.data.mongodb.core.query.Criteria.where; 

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import com.fox.webapp.domain.Account;
import com.fox.webapp.domain.CommissionRecord;
import com.fox.webapp.persistent.custom.CommissionRecordRepositoryCustom;

/**
 * @author yockii
 *
 */
public class CommissionRecordRepositoryImpl implements
		CommissionRecordRepositoryCustom {

	@Autowired
	private MongoTemplate mongoTemplate;
	
	/* (non-Javadoc)
	 * @see com.fox.webapp.persistent.custom.CommissionRecordRepositoryCustom#findAllMyAccountsCommissionRecord(java.util.List, org.springframework.data.domain.PageRequest)
	 */
	@Override
	public Page<CommissionRecord> findAllMyAccountsCommissionRecord(
			List<Account> accounts, Pageable pageRequest) {
		if(accounts == null || accounts.size() == 0){
			return null;
		}
		Criteria c = new Criteria();
		List<Criteria> cList = new ArrayList<Criteria>();
		for (Account account : accounts) {
			cList.add(where("accountNo").is(account.getAccountNo()).andOperator(where("brokerName").is(account.getBroker().getName().toLowerCase())));
		}
		c.orOperator(cList.toArray(new Criteria[cList.size()]));
		Query q = new Query(c);
		q.with(pageRequest);
		
		return new PageImpl<CommissionRecord>(mongoTemplate.find(q, CommissionRecord.class), pageRequest, mongoTemplate.count(q, CommissionRecord.class));
		
//		return new PageImpl<CommissionRecord>(mongoTemplate.find(q, CommissionRecord.class));
	}

	@Override
	public void updateAllAccountCommission2Backed(String accountNo, String brokerName) {
		Query query = new Query().addCriteria(where("accountNo").is(accountNo)).addCriteria(where("brokerName").regex(Pattern.compile(brokerName, Pattern.CASE_INSENSITIVE)));
		Update update = new Update().set("isBacked", true);
		mongoTemplate.updateMulti(query, update, CommissionRecord.class);
	}

}
